package logic

import (
	"context"
	"fmt"
	"zg1/weipinhui/models/cache"
	"zg1/weipinhui/models/mysql"
	"zg1/weipinhui/pkg"

	"zg1/weipinhui/wphrpc/internal/svc"
	"zg1/weipinhui/wphrpc/wphrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *wphrpc.LoginRequest) (*wphrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := mysql.User{}
	mysql.DB.Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}

	if len(user.Tel) != 11 {
		return nil, fmt.Errorf("手机号不存在")
	}

	cha, err := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if err != nil {
		return nil, err
	}

	if cha != in.ChaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}

	sms, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	return &wphrpc.LoginResponse{
		Id: int64(user.ID),
	}, nil
}
